﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Diagnostics;

namespace Patterns.SafeCode
{
	/// <summary>
	/// 	Provides delegate automation with exception sensitivity.
	/// </summary>
	public static class Try
	{
		/// <summary>
		/// 	Gets the result of the specified getter.
		/// </summary>
		/// <typeparam name = "T"></typeparam>
		/// <param name = "getter">The getter.</param>
		/// <param name = "handler">The error handler.</param>
		/// <returns></returns>
		public static T Get<T>(Func<T> getter, Action<Exception> handler = null)
		{
			handler = handler ?? HandleErrors.DefaultStrategy;

			try
			{
				return getter();
			}
			catch (Exception ex)
			{
				Do(() => handler(ex));
			}

			return default(T);
		}

		/// <summary>
		/// 	Does the specified action.
		/// </summary>
		/// <param name = "action">The action.</param>
		/// <param name = "handler">The error handler.</param>
		public static void Do(Action action, Action<Exception> handler = null)
		{
			handler = handler ?? HandleErrors.DefaultStrategy;

			try
			{
				action();
			}
			catch (Exception ex)
			{
				Do(() => handler(ex));
			}
		}

		#region Nested type: HandleErrors

		/// <summary>
		/// Defines error-handling strategies used by <see cref="Try"/>.
		/// </summary>
		public static class HandleErrors
		{
			static HandleErrors()
			{
				DefaultStrategy = error => Debug.WriteLine(error.ToString());
			}

			/// <summary>
			/// Gets or sets the default strategy.
			/// </summary>
			/// <value>The default strategy.</value>
			public static Action<Exception> DefaultStrategy { get; set; }
		}

		#endregion
	}
}